package com.chen.blue.aop;

import cn.hutool.json.JSONUtil;
import com.chen.blue.annotation.RepeatSubmit;
import com.chen.blue.constant.HttpStatus;
import com.chen.blue.exception.e.NoRepeatException;
import com.chen.blue.result.R;
import com.chen.blue.service.security.SecurityService;
import com.chen.blue.utils.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created By CLT On 2024/6/4.
 */
@SuppressWarnings("all")
@Slf4j
@Aspect
@Component
public class NoRepeatSubmit {

    Map<String, Map<String, Long>> repeatSubmitCache = new ConcurrentHashMap<>();
    Map<String, Long> data = null;

    @Before("@annotation(repeatSubmit)")
    public void noRepeatSubmit(JoinPoint joinPoint, RepeatSubmit repeatSubmit) {

        String currentUserName = SecurityService.currentUserName();
        String currentRequestStr = ServletUtil.getCurrentURL();

        if (repeatSubmitCache.containsKey(currentUserName)) {

            Map<String, Long> stringLongMap = repeatSubmitCache.get(currentUserName);
            if (stringLongMap.containsKey(currentRequestStr)) {

                long lastRequestTime = stringLongMap.get(currentRequestStr);
                long currentRequestTime = System.currentTimeMillis();
                if (currentRequestTime - lastRequestTime <= repeatSubmit.interval()) {
                    throw new NoRepeatException("重复提交");
                }
                stringLongMap.put(currentRequestStr, currentRequestTime);

            }

        } else {
            data = new ConcurrentHashMap<>();
            data.put(currentRequestStr, System.currentTimeMillis());
            repeatSubmitCache.put(currentUserName, data);
        }

    }


}
